<?php

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

//    require_once (JPATH_COMPONENT . DS . 'classes' . DS . 'fpdf' . DS . 'fpdf.php');
/**
 * Component Controller
 * @since 1.0
 */
class TaxiBookingController extends JController {

    /**
     * Constructor
     *
     * @since 1.0
     */
    function __construct() {

        parent::__construct();
    }

    /**
     * Display the view
     */
    function display() {

        // View caching logic -- simple... are we logged in?
        // Crappy joomla caching...its a fix t exclude certain items from caching
        // see: http://joomlacode.org/gf/project/joomla/tracker/?action=TrackerItemEdit&tracker_item_id=10840
        $user = &JFactory::getUser();
        if ($user->get('id') || JRequest::getVar('view') == 'category') {
//                       var_dump($query);
//    die;
            parent::display(false);
        } else {
            parent::display(true);
        }
    }

    /**
     * Get price according to the user's choice
     *
     * @access	public
     * @since	1.0
     */
    public function getPrice() {

        // Check for request forgeries
        // Initialize variables
        $db = & JFactory::getDBO();
        $user = & JFactory::getUser();
        $session = & JFactory::getSession();

        // Get the component configuration
        $elsettings = & booking_helper::config();

        //get data from request

        $post = $_REQUEST;

        if (isset($post['from_dest'])) {
            $from_dest_val = $post['from_dest'];
        } else{
            $from_dest_val = -1;
        }
        $session->set('from_dest', $from_dest_val);
        
        if (isset($post['to_dest'])) {
            $to_dest_val = $post['to_dest'];
        } else {
            $to_dest_val = -1;
        }
        $session->set('to_dest', $to_dest_val);


        $airports1_val = "";
        $zipcode1_val = "";
        $seaports1_val = "";

        switch ($from_dest_val) {
            case 0:
                if (isset($post['airports1']) && ($post['airports1'] != "")) {
                    $airports1_val = $post['airports1'];
                    $session->set('airports1', $airports1_val);
                    $session->set('from_error', '');
                } else {
                    $session->set('airports1', '');
                    $session->set('from_error', 'Taxi from Airports is empty!');
                }
                break;
            case 1:
                //if(isset($post['zipcode1']) && ($post['zipcode1'] != "")) {
                $zipcodes1 = array();
                if (isset($post['street1']) && ($post['street1'] != "")) {
                    $zipcodes1[] = $post['street1'];
                    $session->set('street1', $post['street1']);
                } else {
                    $session->set('street1', '');
                }

                if (isset($post['town1']) && ($post['town1'] != "")) {
                    $zipcodes1[] = $post['town1'];
                    $session->set('town1', $post['town1']);
                } else {
                    $session->set('town1', '');
                }
                if (isset($post['county1']) && ($post['county1'] != "")) {
                    $zipcodes1[] = urldecode($post['county1']);
                    $session->set('county1', $post['county1']);
                } else {
                    $session->set('county1', '');
                }
                if (isset($post['district1']) && ($post['district1'] != "")) {
                    $zipcodes1[] = $post['district1'];
                    $session->set('district1', $post['district1']);
                } else {
                    $session->set('district1', '');
                }
                if (isset($post['postcode1']) && ($post['postcode1'] != "")) {
                    $zipcodes1[] = $post['postcode1'];
                    $session->set('postcode1', $post['postcode1']);
                } else {
                    $session->set('postcode1', '');
                }

                if (isset($post['country1']) && ($post['country1'] != "")) {
                    $zipcodes1[] = $post['country1'];
                    $session->set('country1', $post['country1']);
                } else {
                    $session->set('country1', '');
                }

                //$zipcode1_val = $post['zipcode1'];
                $zipcode1_val = ( count($zipcodes1) ? implode(',', $zipcodes1) : '' );
                $session->set('zipcode1', $zipcode1_val);
                $session->set('from_error', '');
                /* } else {
                  $session->set('zipcode1', '');
                  $session->set('postcode1', '');
                  $session->set('from_error', 'Disctrict field can not be empty! You must choose District.');
                  } */
                break;
            case 2:
                if (isset($post['seaports1']) && ($post['seaports1'] != "")) {
                    $seaports1_val = $post['seaports1'];
                    $session->set('seaports1', $seaports1_val);
                    $session->set('from_error', '');
                } else {
                    $session->set('seaports1', '');
                    $session->set('from_error', 'Taxi from Seaports is empty!');
                }
                break;
        }

        $airports2_val = "";
        $zipcode2_val = "";
        $seaports2_val = "";

        switch ($to_dest_val) {
            case 0:
                if (isset($post['airports2']) && ($post['airports2'] != "")) {
                    $airports2_val = $post['airports2'];
                    $session->set('airports2', $airports2_val);
                    $session->set('to_error', '');
                } else {
                    $session->set('airports2', '');
                    $session->set('to_error', 'Taxi to Airports is empty!');
                }
                break;
            case 1:
                //if(isset($post['zipcode2']) && ($post['zipcode2'] != "")) {

                $zipcodes2 = array();
                if (isset($post['street2']) && ($post['street2'] != "")) {
                    $zipcodes2[] = $post['street2'];
                    $session->set('street2', $post['street2']);
                } else {
                    $session->set('street2', '');
                }

                if (isset($post['town2']) && ($post['town2'] != "")) {
                    $zipcodes2[] = $post['town2'];
                    $session->set('town2', $post['town2']);
                } else {
                    $session->set('town2', '');
                }
                if (isset($post['county2']) && ($post['county2'] != "")) {
                    $zipcodes2[] = urldecode($post['county2']);
                    $session->set('county2', $post['county2']);
                } else {
                    $session->set('county2', '');
                }
                if (isset($post['district2']) && ($post['district2'] != "")) {
                    $zipcodes2[] = $post['district2'];
                    $session->set('district2', $post['district2']);
                } else {
                    $session->set('district2', '');
                }
                if (isset($post['postcode2']) && ($post['postcode2'] != "")) {
                    $zipcodes2[] = $post['postcode2'];
                    $session->set('postcode2', $post['postcode2']);
                } else {
                    $session->set('postcode2', '');
                }

                if (isset($post['country2']) && ($post['country2'] != "")) {
                    $zipcodes2[] = $post['country2'];
                    $session->set('country2', $post['country2']);
                } else {
                    $session->set('country2', '');
                }

                $zipcode2_val = ( count($zipcodes2) ? implode(',', $zipcodes2) : '' );
                $session->set('zipcode2', $zipcode2_val);
                $session->set('to_error', '');

                /* } else {
                  $session->set('postcode2', '');
                  $session->set('zipcode2', '');
                  $session->set('to_error', 'Disctrict field can not be empty! You must choose District.');
                  } */
                break;
            case 2:
                if (isset($post['seaports2']) && ($post['seaports2'] != "")) {
                    $seaports2_val = $post['seaports2'];
                    $session->set('seaports2', $seaports2_val);
                    $session->set('to_error', '');
                } else {
                    $session->set('seaports2', '');
                    $session->set('to_error', 'Taxi to Seaports is empty!');
                }
                break;
        }
        
        if (isset($post['fixed_route']) && ($post['fixed_route'] != "")) {
            $session->set('from_error', '');
            $session->set('to_error', '');
            $fixed_route = $post['fixed_route'];
        } else {
            $fixed_route = "";
        }
        $session->set('fixed_route', $fixed_route);

        if (isset($post['returnjurney'])) {
            $session->set('returnjurney', 1);
            $returnjurney = 1;
        } else {
            $returnjurney = 0;
            $session->set('returnjurney', 0);
        }

        if (isset($post['passengers']) && ($post['passengers'] > 0)) {
            $session->set('passengers', $post['passengers']);
            $passengers = $post['passengers'];
            $session->set('passenger_error', '');
        } else {
            $session->set('passenger_error', 'Passengers number is 0!');
            $passengers = "";
        }

        if (isset($post['infantseats'])) {
            $session->set('infantseats', $post['infantseats']);
            $infantseats = $post['infantseats'];
        } else
            $infantseats = "";

        if (isset($post['chseats'])) {
            $session->set('chseats', $post['chseats']);
            $chseats = $post['chseats'];
        } else
            $chseats = "";

        if (isset($post['boosterseats'])) {
            $session->set('boosterseats', $post['boosterseats']);
            $boosterseats = $post['boosterseats'];
        } else
            $boosterseats = "";

        if (isset($post['suitcases'])) {
            $session->set('suitcases', $post['suitcases']);
            $suitcases = $post['suitcases'];
        } else
            $suitcases = "";

        if (isset($post['vehicle'])) {
            $session->set('vehicle', $post['vehicle']);
        }

        if ($from_dest_val == 1 && $to_dest_val == 1) {
            //$session->set('zip_error', 'Sorry but til now we can transfer you only FROM or TO airports or seaports');
        }

        $zip_error = $session->get('zip_error', '');


        if ($passengers == '') {
            $passengers_error = $session->get('passenger_error', '');
        } else {
            $passengers_error = "";
        }
        
        if (isset($post['from_dest']) &&
                (($airports1_val != "") || ($zipcode1_val != "") || ($seaports1_val != "") || ($fixed_route != "")) &&
                isset($post['to_dest']) &&
                (($airports2_val != "") || ($zipcode2_val != "") || ($seaports2_val != "") || ($fixed_route != "")) &&
                ($zip_error == "") && ($passengers_error == "")
        ) {
            
            // if fixed route is selected
            $price = 0;
            if($fixed_route != ""){
                $begin = booking_helper::get_route_field($fixed_route, 'from');
                $session->set('begin', $begin);

                $end = booking_helper::get_route_field($fixed_route, 'to');
                $session->set('end', $end);
                
                $price += booking_helper::get_route_field($fixed_route, 'price');
            
            }else {
            
                switch ($from_dest_val) {
                    case 0:
                        $begin = $airports1_val;
                        break;
                    case 1:
                        $begin = $zipcode1_val;
                        break;
                    case 2:
                        $begin = $seaports1_val;
                        break;
                }

                switch ($to_dest_val) {
                    case 0:
                        $end = $airports2_val;
                        break;
                    case 1:
                        $end = $zipcode2_val;
                        break;
                    case 2:
                        $end = $seaports2_val;
                        break;
                }

                if ($this->getLatLong($begin, $session->get('from_dest'))) {
                    $session->set('begin', $begin);
                    $lat_long_from = $this->getLatLong($begin, $session->get('from_dest'));
                    $session->set('lat_long_from', $lat_long_from);
                }

                if ($this->getLatLong($end, $session->get('to_dest'))) {
                    $session->set('end', $end);
                    $lat_long_to = $this->getLatLong($end, $session->get('to_dest'));
                    $session->set('lat_long_to', $lat_long_to);
                }

                $dist_miles = ceil($this->calculateDistance($lat_long_from['lat'], $lat_long_from['long'], $lat_long_to['lat'], $lat_long_to['long'], $elsettings->distance_unit));

                $session->set('dist_miles', $dist_miles);

                $correction = 0;

            //if ($dist_miles > 5)		
            //{
                if ($dist_miles <= $elsettings->minmil){
                    $price += $elsettings->minprice;
                }else{
                    $price += ($dist_miles * $elsettings->price_per_unit_distance ) + $elsettings->cost_per_call;
                }
            }

            $vehicletype = $session->get('vehicle', -1);
            $selcarry = 0;
            $selpsg = $session->get('passengers', 0);
            $suitcases = $session->get('suitcases', 0);
            $infantseats = $session->get('infantseats', 0);
            $chseats = $session->get('chseats', 0);
            $boosterseats = $session->get('boosterseats', 0);
                
            /*if (($selpsg > 5) || ($suitcases > 5)) {
                $price += $elsettings->seat8_price;
            } elseif ((($selpsg > 4) || ($suitcases >= 4)) && (($selpsg <= 5) || ($suitcases <= 5))) {
                $price += $elsettings->mpv_price;
            }*/
            
            if($vehicletype == 1)
            {
                    $price += $elsettings->mpv_price;
            }
            elseif($vehicletype == 2)
            {						
                    $price += $elsettings->seat8_price;
            }

            if ($infantseats > 0) {
                $price += $infantseats * $elsettings->infant_seat_price;
            }
            if ($chseats > 0) {
                $price += $chseats * $elsettings->child_seat_price;
            }
            if ($boosterseats > 0) {
                $price += $boosterseats * $elsettings->booster_seat_price;
            }

            //if ($from_dest == 0) $price += 6;	//6 pounds taxa - za posreshtane ot letishte 
            //if ($returnjurney==1) $price = round(2*($price-$elsettings->discount*$price/100));
            if ($returnjurney == 1) {
                $price = (2 * $price) - ( $elsettings->discount * $price / 100 ) + $elsettings->pick_up_charge;
            }

            //$price = number_format($price, 2, '.', ',');
            $session->set('price', $price);
            $session->set('formatted_price', number_format($price, 2, '.', ','));

            /* }else {
              $this->setRedirect(JRoute::_('index.php?option=com_taxibooking', false), 'ERROR: [WRONG ADDRESS]');
              } */
// var_dump($dist_miles);
//                     die;
            
            $this->setRedirect(JRoute::_('index.php?option=com_taxibooking&view=confirm', false));
        } else {
            $this->setRedirect(JRoute::_('index.php?option=com_taxibooking', false));
        }
    }

    /**
     * Get latitude logitude according to the address
     *
     * @access	public
     * @since	1.0
     */
    function getLatLong($address, $address_type = 0) {
        global $mainframe;

        // Get the page/component configuration
        $elsettings = & booking_helper::config();
//            echo '<pre>';
//            print_r($elsettings);
        //$params->set('gmap_key', 'ABQIAAAAfl609FaKG0dc57AYZn90PRSPf0glJUQSEPxjWBTAAsDpTeniFRTVd97fSyX4ZwEO-HC56aTnYs5DfA');
        $elsettings->gmap_key = 'ABQIAAAAfl609FaKG0dc57AYZn90PRSPf0glJUQSEPxjWBTAAsDpTeniFRTVd97fSyX4ZwEO-HC56aTnYs5DfA';
        if ($address == "") {

            return null;
        }

        $key = $elsettings->gmap_key;

        if ($key == "") {

            return null;
        }

        if ($address_type == 0) {

            $latitude_longitude = array();

            $latitude_longitude['lat'] = booking_helper::get_place_field($address, 'lat');
            $latitude_longitude['long'] = booking_helper::get_place_field($address, 'long');

            return $latitude_longitude;
        } else {
             // Desired address
                $address	= rawurlencode($address);	
                $address 	= "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";
    
                // Retrieve the URL contents
                try {
                        $page = file_get_contents($address);
                        $page = mb_convert_encoding($page, "UTF-8");

                        // Parse the returned json file
                        $response = json_decode($page);

                        // Parse the coordinate string
                        if($response->status == 'OK'){

                            $latitude_longitude = array ();

                           // Output the coordinates
                            $latitude_longitude['lat']=$response->results[0]->geometry->location->lat;
                            $latitude_longitude['long']=$response->results[0]->geometry->location->lng;

                            return $latitude_longitude;	
                        }
                        else{
                                return null;
                        }

                }
                catch (Exception $e)
                {
                        return null;
                }
        }
    }

    /**
     * Logic to Calculate distance between two address
     *
     * @access	public
     * @since	1.0
     */
    function calculateDistance($lat1, $lon1, $lat2, $lon2, $unit) {
        try {
            $q = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={$lat1},{$lon1}&destinations={$lat2},{$lon2}&mode=driving&sensor=false";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $q);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $json = curl_exec($ch);
            curl_close($ch);

//                $json = file_get_contents('http://yahoo.com');
            $details = json_decode($json, TRUE);
//                var_dump($details);
            $distance = $details['rows'][0]['elements'][0]['distance']['value'];
            $distance_km = $distance / 1000;

            //$unit = strtoupper($unit);

            if ($unit == "kM") {
                return $distance_km;
            } else {
                return ($distance_km / 1.609344);
            }
        } catch (Exception $e) {
            return 0;
        }

        /* $theta = $lon1 - $lon2; 
          $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
          $dist = acos($dist);
          $dist = rad2deg($dist);
          $miles = $dist * 60 * 1.1515;*
          $unit = strtoupper($unit);

          if ($unit == "K") {
          return ($miles * 1.609344);
          } else if ($unit == "N") {
          return ($miles * 0.8684);
          } else {
          return $miles;
          } */
    }

    /**
     * Get the personal details and proceed to preview order
     *
     * @access	public
     * @since	1.0
     */
    function previewOrder() {

        // Check for request forgeries
        JRequest::checkToken() or jexit('Invalid Token');

        global $mainframe;

        // Initialize variables
        $db = & JFactory::getDBO();
        $user = & JFactory::getUser();
        $session = & JFactory::getSession();

        // Get the page/component configuration
        $elsettings = & booking_helper::config();
// To restrict the booking time from current time
        $restrict_time = $elsettings->restrict_time;
        $restrict_time = round($restrict_time * 60);
        //get data from request
        $post = JRequest::get('post');

        if (isset($post['name']) && $post['name'] == "") {
            $name_val = $post['name'];
            $session->set('name_error', 'Please enter your name.');
            $session->set('name', '');
        } elseif (isset($post['name']) && $post['name'] != "") {
            $name_val = $post['name'];
            $session->set('name', $post['name']);
            $session->set('name_error', '');
        }
        if (isset($post['surname']) && $post['surname'] == "") {
            $surname_val = $post['surname'];
            $session->set('surname', $post['surname']);
            $session->set('surname_error', 'Please enter your surname.');
        } elseif (isset($post['surname']) && $post['surname'] != "") {
            $surname_val = $post['surname'];
            $session->set('surname', $post['surname']);
            $session->set('surname_error', '');
        }
        if (isset($post['email']) && $post['email'] == "") {
            $email_val = $post['email'];
            $session->set('email', $post['email']);
            $session->set('email_error', 'Please enter your e-mail.');
        } elseif (isset($post['email']) && !booking_helper::is_valid_email($post['email'])) {
            $email_val = $post['email'];
            $session->set('email', $post['email']);
            $session->set('email_error', 'Please enter a valid e-mail.');
        } elseif (isset($post['email']) && $post['email'] != "") {
            $email_val = $post['email'];
            $session->set('email', $post['email']);
            $session->set('email_error', '');
        }
        if (isset($post['phone']) && $post['phone'] == "") {
            $phone_val = $post['phone'];
            $session->set('phone', $post['phone']);
            $session->set('phone_error', 'Please enter your phone.');
        } elseif (!booking_helper::is_valid_phone($post['phone'])) {
            $phone_val = $post['phone'];
            $session->set('phone', $post['phone']);
            $session->set('phone_error', 'Please enter a valid phone.');
        } elseif (isset($post['phone']) && $post['phone'] != "") {
            $phone_val = $post['phone'];
            $session->set('phone', $post['phone']);
            $session->set('phone_error', '');
        }


        if (isset($post['PickupAddr1']) && $post['PickupAddr1'] == "") {
            $addr1_val = $post['PickupAddr1'];
            $session->set('PickupAddr1', $addr1_val);
            $session->set('PickupAddr1_error', 'Please enter Details');
        } elseif (isset($post['PickupAddr1']) && $post['PickupAddr1'] != "") {
            $addr1_val = $post['PickupAddr1'];
            $session->set('PickupAddr1', $addr1_val);
            $session->set('PickupAddr1_error', '');
        }

        if ($post["from_dest"] > 0) {
            if (isset($post['PickupAddr2']) && $post['PickupAddr2'] == "") {
                $addr2_val = $post['PickupAddr2'];
                $session->set('PickupAddr2', $addr2_val);
                $session->set('PickupAddr2_error', 'Please enter address2.');
            } elseif (isset($post['PickupAddr2']) && $post['PickupAddr2'] != "") {
                $addr2_val = $post['PickupAddr2'];
                $session->set('PickupAddr2', $addr2_val);
                $session->set('PickupAddr2_error', '');
            }
            if (isset($post['PickupAddr3']) && $post['PickupAddr3'] == "") {
                $addr3_val = $post['PickupAddr3'];
                $session->set('PickupAddr3', $addr3_val);
                $session->set('PickupAddr3_error', 'Please enter address3.');
            } elseif (isset($post['PickupAddr3']) && $post['PickupAddr3'] != "") {
                $addr3_val = $post['PickupAddr3'];
                $session->set('PickupAddr3', $addr3_val);
                $session->set('PickupAddr3_error', '');
            }
        }



        if (isset($post['PickupAddr4']) && $post['PickupAddr4'] == "") {
            $addr4_val = $post['PickupAddr4'];
            $session->set('PickupAddr4', $addr4_val);
            $session->set('PickupAddr4_error', 'Please enter Details');
        } elseif (isset($post['PickupAddr4']) && $post['PickupAddr4'] != "") {
            $addr4_val = $post['PickupAddr4'];
            $session->set('PickupAddr4', $addr4_val);
            $session->set('PickupAddr4_error', '');
        }

        if ($post["to_dest"] > 0) {
            if (isset($post['PickupAddr5']) && $post['PickupAddr5'] == "") {
                $addr5_val = $post['PickupAddr5'];
                $session->set('PickupAddr5', $addr5_val);
                $session->set('PickupAddr5_error', 'Please enter address5.');
            } elseif (isset($post['PickupAddr5']) && $post['PickupAddr5'] != "") {
                $addr5_val = $post['PickupAddr5'];
                $session->set('PickupAddr5', $addr5_val);
                $session->set('PickupAddr5_error', '');
            }
            if (isset($post['PickupAddr6']) && $post['PickupAddr6'] == "") {
                $addr6_val = $post['PickupAddr6'];
                $session->set('PickupAddr6', $addr6_val);
                $session->set('PickupAddr6_error', 'Please enter address6.');
            } elseif (isset($post['PickupAddr6']) && $post['PickupAddr6'] != "") {
                $addr6_val = $post['PickupAddr6'];
                $session->set('PickupAddr6', $addr6_val);
                $session->set('PickupAddr6_error', '');
            }
        }


        if (isset($post['message'])) {
            $message = $post['message'];
            $session->set('message', $message);
        } else
            $message = "";

        if (isset($post["prepay"]))
            $prepay = $this->check_input($post["prepay"]);
        else
            $prepay = 100;

        if (isset($post["orderdate"]))
            $date1 = $this->check_input($post["orderdate"]);
        else
            $date1 = "";

        if (isset($post["selPtHr1"]) && isset($post["selPtMn1"])) {
            $time1 = $this->check_input($post['selPtHr1']) . ":" . $this->check_input($post['selPtMn1']);
        }
        else
            $time1 = "";

        if (isset($post["orderdatereturn"]))
            $date2 = $this->check_input($post["orderdatereturn"]);
        else
            $date2 = "";

        if (isset($post["selPtHr2"]) && isset($post["selPtMn2"])) {
            $time2 = $this->check_input($post['selPtHr2']) . ":" . $this->check_input($post['selPtMn2']);
        }
        else
            $time2 = "";


        $message = $this->check_input($post["message"]);
        $session->set('date1', $date1);
        $session->set('time1', $time1);
        $session->set('date2', $date2);
        $session->set('time2', $time2);
        $session->set('message', $message);


        if ($session->get('date1', '') == '') {
            $msg = 'Please enter departing date.';
            $session->set('date_error', $msg);
        } elseif ((booking_helper::DateTime2($session->get('date1', ''), $session->get('time1', '')) - gmdate("YmdHi")) < $restrict_time) {
            $msg = $session->get('date1', '') . ' ' . $session->get('time1', '') . ' (Insufficient time for accept booking)';
            $session->set('date_error', $msg);
        } else {
            $msg = '';
            $session->set('date_error', $msg);
        }

        if (($session->get('returnjurney', 0) == 1)) {
            if ($session->get('date2', '') == '') {
                $msg = 'Please enter returning date.';
                $session->set('return_date_error', $msg);
            } elseif ((((booking_helper::DateTime2($session->get('date2', ''), $session->get('time2', '')) - booking_helper::DateTime2($session->get('date1', ''), $session->get('time1', '')))) < 0)) {
                $msg = $session->get('date2', '') . ' ' . $session->get('time2', '') . '(Insufficient time)';
                $session->set('return_date_error', $msg);
            } else {
                $msg = '';
                $session->set('return_date_error', $msg);
            }
        }


        if (isset($post['Submitpaypal']) || isset($post['SubmitCash']) || isset($post['Submitncipay']) || isset($post['Submitanzpay'])) {
            if (($post['name'] == "") || ($post['surname'] == "") || ($session->get('email_error', '') != '') || ($session->get('phone_error', '') != '') ||
                    ($session->get('PickupAddr1_error', '') != "") || ($session->get('PickupAddr2_error', '') != "") || ($session->get('PickupAddr3_error', '') != "") ||
                    ($session->get('PickupAddr4_error', '') != "") || ($session->get('PickupAddr5_error', '') != "") || ($session->get('PickupAddr6_error', '') != "") ||
                    ($session->get('date_error', '') != "") || ($session->get('return_date_error', '') != "")) {
                $this->setRedirect(JRoute::_('index.php?option=com_taxibooking&view=confirm', false));
            } else {
                $title = $this->check_input($post["title"]);
                $name = $this->check_input($post["name"]);
                $surname = $this->check_input($post["surname"]);
                $email = $this->check_input($post["email"]);
                $phone = $this->check_input($post["phone"]);
                $returntrip = $this->check_input($post["returntrip"]);
                $cprice = $this->check_input($post["cprice"]); //echo"cprice =  $this->check_input".$cprice;

                $selpsg = $this->check_input($post["selpsg"]);
                $suitcases = $this->check_input($post["suitcases"]);
                $infantseats = $this->check_input($post["infantseats"]);
                $chseats = $this->check_input($post["chseats"]);
                $boosterseats = $this->check_input($post["boosterseats"]);
//			$selluggage =  $this->check_input( $post["selluggage"]);
                $selcarry = $this->check_input($post["selcarry"]);
                $vehicletype = $this->check_input($post["vehicletype"]);

                $PickupAddr1 = $this->check_input($post["PickupAddr1"]);
                $PickupAddr2 = $this->check_input($post["PickupAddr2"]);
                $PickupAddr3 = $this->check_input($post["PickupAddr3"]);
                $PickupAddr4 = $this->check_input($post["PickupAddr4"]);
                $PickupAddr5 = $this->check_input($post["PickupAddr5"]);
                $PickupAddr6 = $this->check_input($post["PickupAddr6"]);

                //echo "XAXAXAXA: ".$post['orderdate']." ".$post['selPtHr1']." ".$post['selPtMn1'];
                //echo "<br>XAXAXAXA: ".$post['orderdatereturn']." ".$post['selPtHr2']." ".$post['selPtMn2'];

                $begin = $this->check_input($post["begin"]);
                $end = $this->check_input($post["end"]);
                $from_dest = $this->check_input($post["from_dest"]);
                $to_dest = $this->check_input($post["to_dest"]);

                $session->set('begin', $begin);
                $session->set('end', $end);
                $session->set('temp1', $from_dest);
                $session->set('temp2', $to_dest);

                $session->set('gender', $this->check_input($post["title"]));
                $session->set('name', $this->check_input($post["name"]));
                $session->set('surname', $this->check_input($post["surname"]));
                $session->set('email', $this->check_input($post["email"]));
                $session->set('phone', $this->check_input($post["phone"]));
                $session->set('returntrip', $this->check_input($post["returntrip"]));
                $session->set('cprice', $this->check_input($post["cprice"])); //echo "SESSION cprice".$session->set('cprice'];
                $session->set('prepay', $prepay);

                $session->set('selpassengers', $this->check_input($post["selpsg"]));
                $session->set('selsuitcases', $this->check_input($post["suitcases"]));
                $session->set('selinfantseats', $this->check_input($post["infantseats"]));
                $session->set('selchildseats', $this->check_input($post["chseats"]));
                $session->set('selboosterseats', $this->check_input($post["boosterseats"]));
//			$session->set('selluggage', $this->check_input( $post["selluggage"]);
                $session->set('selcarry', $this->check_input($post["selcarry"]));
                $session->set('vehicletype', $this->check_input($post["vehicletype"]));

                $session->set('PickupAddr1', $this->check_input($post["PickupAddr1"]));
                $session->set('PickupAddr2', $this->check_input($post["PickupAddr2"]));
                $session->set('PickupAddr3', $this->check_input($post["PickupAddr3"]));
                $session->set('PickupAddr4', $this->check_input($post["PickupAddr4"]));
                $session->set('PickupAddr5', $this->check_input($post["PickupAddr5"]));
                $session->set('PickupAddr6', $this->check_input($post["PickupAddr6"]));

                if (isset($post['Submitpaypal'])) {
                    $session->set('submittype', 'Submitpaypal');
                } elseif (isset($post['SubmitCash'])) {
                    $session->set('submittype', 'SubmitCash');
                } elseif (isset($post['Submitncipay'])) {
                    $session->set('submittype', 'Submitncipay');
                } elseif (isset($post['Submitanzpay'])) {
                    $session->set('submittype', 'Submitanzpay');
                }


                // add surchage by order date
                $price = $session->get('cprice', '');
                $total_surcharge = 0;
                $surcharge_by_dates = $elsettings->surcharge_by_dates;
                if ($surcharge_by_dates != '') {
                    $surcharge_by_dates_arr = explode(',', $surcharge_by_dates);

                    foreach ($surcharge_by_dates_arr as $surcharge_by_date) {
                        $item_arr = explode('-', $surcharge_by_date);
                        $surchage_date = (isset($item_arr[0]) ) ? $item_arr[0] : '';
                        $surchage = (isset($item_arr[1]) ) ? $item_arr[1] : 0;

                        if ($surchage_date == $date1) {
                            $total_surcharge += $surchage;
                            $price += ($price * $surchage / 100);
                        } elseif ($surchage_date == $date2) {
                            $total_surcharge += $surchage;
                            $price += ($price * $surchage / 100);
                        }
                    }
                }
                //$price = number_format($price, 2, '.', ',');
                $price = ceil($price);
                //echo $total_surcharge.'<br>'.$price;
                $session->set('total_surcharge', $total_surcharge);
                $session->set('cprice', $price);
                $session->set('formatted_price', number_format($price, 2, '.', ','));
                // end adding surcharge

                $this->setRedirect(JRoute::_('index.php?option=com_taxibooking&view=summary', false));
            }
        }
    }

    /**
     * Check all the input values
     *
     * @access	public
     * @since	1.0
     */
    function check_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES);
        //no	$data = htmlentities($data);
        return $data;
    }

    /**
     * Submit the order info into database
     *
     * @access	public
     * @since	1.0
     */
    function submitOrder() {
        // Check for request forgeries
        JRequest::checkToken() or jexit('Invalid Token');

//            global $mainframe;
        // Initialize variables
        $db = & JFactory::getDBO();
        $user = & JFactory::getUser();
        $session = & JFactory::getSession();

        // Get the page/component configuration
        $elsettings = & booking_helper::config();

        // check whether session is still alive
        if ($session->get('dist_miles', 0) == 0) {
            $mainframe->redirect(JRoute::_('index.php?option=com_taxibooking', false), 'Session Expired. Please book again.');
        }

        //get data from request
        $post = JRequest::get('post');

        if ($session->get('submittype') == 'SubmitCash') {
            $security_code = $session->get('security_code', '');

            if ($security_code != $post['security_code']) {
                $err = '<span style="color: #ff0000; font-size: 8pt; font-family: Verdana, Arial, Helvetica, sans-serif;"><b><i> Sorry, you have provided an invalid security code.</i></b></span><br>';
                $session->set('security_code_error', $err);

                $this->setRedirect(JRoute::_('index.php?option=com_taxibooking&view=summary', false));
            } else {
                $session->set('security_code_error', '');

                $title = $this->check_input($session->get("gender", ""));
                $name = $this->check_input($session->get("name", ""));
                $surname = $this->check_input($session->get("surname", ""));
                $email = $this->check_input($session->get("email", ""));
                $phone = $this->check_input($session->get("phone", ""));
                $returntrip = $this->check_input($session->get("returntrip", ""));
                $cprice = $this->check_input($session->get("cprice", ""));
                $prepay = $this->check_input($session->get("prepay", ""));

                $selpassengers = $this->check_input($session->get("selpassengers", ""));
                $selsuitcases = $this->check_input($session->get("selsuitcases", ""));
                $selinfantseats = $this->check_input($session->get("selinfantseats", ""));
                $selchildseats = $this->check_input($session->get("selchildseats", ""));
                $selboosterseats = $this->check_input($session->get("selboosterseats", ""));
//			$selluggage = $this->check_input($session->get("selluggage", ""));
                $selcarry = $this->check_input($session->get("selcarry", ""));
                $vehicletype = $this->check_input($session->get("vehicletype", ""));

                $PickupAddr1 = $this->check_input($session->get("PickupAddr1", ""));
                $PickupAddr2 = $this->check_input($session->get("PickupAddr2", ""));
                $PickupAddr3 = $this->check_input($session->get("PickupAddr3", ""));
                $PickupAddr4 = $this->check_input($session->get("PickupAddr4", ""));
                $PickupAddr5 = $this->check_input($session->get("PickupAddr5", ""));
                $PickupAddr6 = $this->check_input($session->get("PickupAddr6", ""));

                $date1 = $this->check_input($session->get("date1", ""));
                $date2 = $this->check_input($session->get("date2", ""));
                $time1 = $this->check_input($session->get("time1", ""));
                $time2 = $this->check_input($session->get("time2", ""));
                $message = $this->check_input($session->get("message", ""));

                $begin = $this->check_input($session->get("begin", ""));
                $end = $this->check_input($session->get("end", ""));
                $from_dest = $this->check_input($session->get("temp1", ""));
                $to_dest = $this->check_input($session->get("temp2", ""));

                if ($from_dest == 0) {
                    $begin = booking_helper::get_place_field($begin, 'title');
                }
                if ($to_dest == 0) {
                    $end = booking_helper::get_place_field($end, 'title');
                }

                // now save this order
                $query = 'INSERT INTO #__taxibooking_orders SET '
                        . ' names = ' . $db->quote($name . ' ' . $surname) . ', '
                        . ' gender = ' . $db->quote($title) . ', '
                        . ' email = ' . $db->quote($email) . ', '
                        . ' phone = ' . $db->quote($phone) . ', '
                        . ' returntrip = ' . $db->quote($returntrip) . ', '
                        . ' cprice = ' . $db->quote($cprice) . ', '
                        . ' prepay = ' . $db->quote($prepay) . ', '
                        . ' selpassengers = ' . $db->quote($selpassengers) . ', '
                        . ' selinfantseats = ' . $db->quote($selinfantseats) . ', '
                        . ' selchildseats = ' . $db->quote($selchildseats) . ', '
                        . ' selboosterseats = ' . $db->quote($selboosterseats) . ', '
                        . ' selluggage = ' . $db->quote($selsuitcases) . ', '
                        . ' selcarry = ' . $db->quote($selcarry) . ', '
                        . ' PickupAddr1 = ' . $db->quote($PickupAddr1) . ', '
                        . ' PickupAddr2 = ' . $db->quote($PickupAddr2) . ', '
                        . ' PickupAddr3 = ' . $db->quote($PickupAddr3) . ', '
                        . ' PickupAddr4 = ' . $db->quote($PickupAddr4) . ', '
                        . ' PickupAddr5 = ' . $db->quote($PickupAddr5) . ', '
                        . ' PickupAddr6 = ' . $db->quote($PickupAddr6) . ', '
                        . ' datetime1 = ' . $db->quote(booking_helper::DateTime2($date1, $time1)) . ', '
                        . ' datetime2 = ' . $db->quote(booking_helper::DateTime2($date2, $time2)) . ', '
                        . ' message = ' . $db->quote($message) . ', '
                        . ' begin = ' . $db->quote($begin) . ', '
                        . ' end = ' . $db->quote($end) . ', '
                        . ' from_dest = ' . $db->quote($from_dest) . ', '
                        . ' to_dest = ' . $db->quote($to_dest) . ', '
                        . ' confirm = ' . $db->quote(uniqid()) . ', '
                        . ' state = "-2", '
                        . ' driver_id = "",'
                        . ' payment = ' . $db->quote('cash') . ', '
                        . ' vehicletype = ' . $db->quote($vehicletype) . ', '
                        . ' created = NOW()';

                $db->setQuery($query);
                if (!$db->query()) {
                    JError::raiseError(500, $db->getErrorMsg());
                    return false;
                }
                $order_id = $db->insertid();

                $this->sendMailDetailsToOwner($order_id);



                // unset all the values
                $session->clear('cart');
                $session->clear('from_dest');
                $session->clear('to_dest');
                $session->clear('airports1');
                $session->clear('zipcode1');
                $session->clear('county1');
                $session->clear('seaports1');
                $session->clear('airports2');
                $session->clear('zipcode2');
                $session->clear('county2');
                $session->clear('seaports2');

                $session->clear('returnjurney');
                $session->clear('infantseats');
                $session->clear('chseats');
                $session->clear('boosterseats');
                $session->clear('vehicle');

                $session->clear('SubmitCash');

                $session->clear('date1');
                $session->clear('time1');
                $session->clear('date2');
                $session->clear('time2');
                $session->clear('message');

                $session->clear('begin');
                $session->clear('end');
                $session->clear('temp1');
                $session->clear('temp2');

                $session->clear('title');
                $session->clear('name');
                $session->clear('surname');
                $session->clear('email');
                $session->clear('phone');
                $session->clear('returntrip');
                $session->clear('cprice');
                $session->clear('prepay');

                $session->clear('passengers');
                $session->clear('infantseats');
                $session->clear('chseats');
                $session->clear('boosterseats');
                $session->clear('suitcases');
                $session->clear('selpassengers');
                $session->clear('selsuitcases');
                $session->clear('selinfantseats');
                $session->clear('selchildseats');
                $session->clear('selboosterseats');
                $session->clear('selluggage');
                $session->clear('selcarry');
                $session->clear('vehicletype');

                $session->clear('PickupAddr1');
                $session->clear('PickupAddr2');
                $session->clear('PickupAddr3');
                $session->clear('PickupAddr4');
                $session->clear('PickupAddr5');
                $session->clear('PickupAddr6');

                $this->setRedirect(JRoute::_('index.php?option=com_taxibooking&view=thanks', false));
            }
        } elseif ($session->get('submittype') == 'Submitpaypal') {
            $title = $this->check_input($session->get("gender", ""));
            $name = $this->check_input($session->get("name", ""));
            $surname = $this->check_input($session->get("surname", ""));
            $email = $this->check_input($session->get("email", ""));
            $phone = $this->check_input($session->get("phone", ""));
            $returntrip = $this->check_input($session->get("returntrip", ""));
            $cprice = $this->check_input($session->get("cprice", ""));
            $prepay = $this->check_input($session->get("prepay", ""));

            $selpassengers = $this->check_input($session->get("selpassengers", ""));
            $selsuitcases = $this->check_input($session->get("selsuitcases", ""));
            $selinfantseats = $this->check_input($session->get("selinfantseats", ""));
            $selchildseats = $this->check_input($session->get("selchildseats", ""));
            $selboosterseats = $this->check_input($session->get("selboosterseats", ""));
//			$selluggage = $this->check_input($session->get("selluggage", ""));
            $selcarry = $this->check_input($session->get("selcarry", ""));
            $vehicletype = $this->check_input($session->get("vehicletype", ""));

            $PickupAddr1 = $this->check_input($session->get("PickupAddr1", ""));
            $PickupAddr2 = $this->check_input($session->get("PickupAddr2", ""));
            $PickupAddr3 = $this->check_input($session->get("PickupAddr3", ""));
            $PickupAddr4 = $this->check_input($session->get("PickupAddr4", ""));
            $PickupAddr5 = $this->check_input($session->get("PickupAddr5", ""));
            $PickupAddr6 = $this->check_input($session->get("PickupAddr6", ""));

            $date1 = $this->check_input($session->get("date1", ""));
            $date2 = $this->check_input($session->get("date2", ""));
            $time1 = $this->check_input($session->get("time1", ""));
            $time2 = $this->check_input($session->get("time2", ""));
            $message = $this->check_input($session->get("message", ""));

            $begin = $this->check_input($session->get("begin", ""));
            $end = $this->check_input($session->get("end", ""));
            $from_dest = $this->check_input($session->get("temp1", ""));
            $to_dest = $this->check_input($session->get("temp2", ""));

            if ($from_dest == 0) {
                $begin = booking_helper::get_place_field($begin, 'title');
            }
            if ($to_dest == 0) {
                $end = booking_helper::get_place_field($end, 'title');
            }

            // now save this order
            $hash_code = uniqid();
            $query = 'INSERT INTO #__taxibooking_orders SET '
                    . ' names = ' . $db->quote($name . ' ' . $surname) . ', '
                    . ' gender = ' . $db->quote($title) . ', '
                    . ' email = ' . $db->quote($email) . ', '
                    . ' phone = ' . $db->quote($phone) . ', '
                    . ' returntrip = ' . $db->quote($returntrip) . ', '
                    . ' cprice = ' . $db->quote($cprice) . ', '
                    . ' prepay = ' . $db->quote($prepay) . ', '
                    . ' selpassengers = ' . $db->quote($selpassengers) . ', '
                    . ' selinfantseats = ' . $db->quote($selinfantseats) . ', '
                    . ' selchildseats = ' . $db->quote($selchildseats) . ', '
                    . ' selboosterseats = ' . $db->quote($selboosterseats) . ', '
                    . ' selluggage = ' . $db->quote($selsuitcases) . ', '
                    . ' selcarry = ' . $db->quote($selcarry) . ', '
                    . ' PickupAddr1 = ' . $db->quote($PickupAddr1) . ', '
                    . ' PickupAddr2 = ' . $db->quote($PickupAddr2) . ', '
                    . ' PickupAddr3 = ' . $db->quote($PickupAddr3) . ', '
                    . ' PickupAddr4 = ' . $db->quote($PickupAddr4) . ', '
                    . ' PickupAddr5 = ' . $db->quote($PickupAddr5) . ', '
                    . ' PickupAddr6 = ' . $db->quote($PickupAddr6) . ', '
                    . ' datetime1 = ' . $db->quote(booking_helper::DateTime2($date1, $time1)) . ', '
                    . ' datetime2 = ' . $db->quote(booking_helper::DateTime2($date2, $time2)) . ', '
                    . ' message = ' . $db->quote($message) . ', '
                    . ' begin = ' . $db->quote($begin) . ', '
                    . ' end = ' . $db->quote($end) . ', '
                    . ' from_dest = ' . $db->quote($from_dest) . ', '
                    . ' to_dest = ' . $db->quote($to_dest) . ', '
                    . ' confirm = ' . $db->quote($hash_code) . ', '
                    . ' state = "-2", '
                    . ' driver_id = "",'
                    . ' payment = ' . $db->quote('paypal') . ', '
                    . ' vehicletype = ' . $db->quote($vehicletype) . ', '
                    . ' created = NOW()';

            $db->setQuery($query);
            if (!$db->query()) {
                JError::raiseError(500, $db->getErrorMsg());
                return false;
            }
            $order_id = $db->insertid();

            $this->sendMailDetailsToOwner($order_id);


            // unset all the values
            $session->clear('cart');
            $session->clear('from_dest');
            $session->clear('to_dest');
            $session->clear('airports1');
            $session->clear('zipcode1');
            $session->clear('county1');
            $session->clear('seaports1');
            $session->clear('airports2');
            $session->clear('zipcode2');
            $session->clear('county2');
            $session->clear('seaports2');

            $session->clear('returnjurney');
            $session->clear('infantseats');
            $session->clear('chseats');
            $session->clear('boosterseats');
            $session->clear('vehicle');

            $session->clear('SubmitCash');

            $session->clear('date1');
            $session->clear('time1');
            $session->clear('date2');
            $session->clear('time2');
            $session->clear('message');

            $session->clear('begin');
            $session->clear('end');
            $session->clear('temp1');
            $session->clear('temp2');

            $session->clear('title');
            $session->clear('name');
            $session->clear('surname');
            $session->clear('email');
            $session->clear('phone');
            $session->clear('returntrip');
            $session->clear('cprice');
            $session->clear('prepay');

            $session->clear('passengers');
            $session->clear('infantseats');
            $session->clear('chseats');
            $session->clear('boosterseats');
            $session->clear('suitcases');
            $session->clear('selpassengers');
            $session->clear('selsuitcases');
            $session->clear('selinfantseats');
            $session->clear('selchildseats');
            $session->clear('selboosterseats');
            $session->clear('selluggage');
            $session->clear('selcarry');
            $session->clear('vehicletype');

            $session->clear('PickupAddr1');
            $session->clear('PickupAddr2');
            $session->clear('PickupAddr3');
            $session->clear('PickupAddr4');
            $session->clear('PickupAddr5');
            $session->clear('PickupAddr6');

            // now redirects to the paypal site
            $itemname = "Taxi from [$begin] to [$end] on [$date1, $time1]";
            if ($returntrip)
                $itemname .= " and return"; // on [$date2, $time2].";
            if ($elsettings->paypal_test_mode == 1) {

                $payment_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
            } else {

                $payment_url = 'https://www.paypal.com/cgi-bin/webscr';
            }

            $paypal_form = "<form name='paypal_form' id='paypal_form' action='{$payment_url}' method='post'>
                            <input type='image' src='https://www.paypal.com/en_US/i/btn/x-click-but02.gif' border='0' name='submit' alt='Make payments with PayPal - it is fast, free and secure!'>
                             <input type='hidden' name='cmd' value='_xclick'>
                             <input type='hidden' name='return' value='" . JURI::base() . "index.php?option=com_taxibooking&task=paypal_thankyou'>
                             <input type='hidden' name='cancel_return' value='" . JURI::base() . "index.php?option=com_taxibooking&task=paypal_cancel'>
                             <input type='hidden' name='notify_url' value='" . JURI::base() . "index.php?option=com_taxibooking&task=paypal_notification'>
                             <input type='hidden' name='cbt' value='Return to \"8seattaxi.co.uk\"'>

                             <input type='hidden' name='business' value ='" . $elsettings->paypal_email . "'>
                             <input type='hidden' name='receiver_email' value='" . $elsettings->paypal_email . "'>

                             <input type='hidden' name='item_name' value='$itemname'>
                             <input type='hidden' name='quantity' value='1'>
                             <input type='hidden' name='amount' value=" . ($prepay * $cprice / 100) . ">
                             <input type='hidden' name='currency_code' value='" . $elsettings->currency . "'>
                             <input type='hidden' name='rm' value='2'>
                             <input type='hidden' name='custom' value='$hash_code'>
                    </form>";

            $html = '<html><body>';
            $html.= JText::_('You will be redirected to PayPal in a few seconds. If you are not, please click on the Paypal link to complete your order.');
            $html.= $paypal_form;
            $html.= '<script type="text/javascript">document.getElementById("paypal_form").submit();</script>';
            $html.= '</body></html>';

            echo $html;
            exit();
        } elseif ($session->get('submittype') == 'Submitncipay') {
            $title = $this->check_input($session->get("gender", ""));
            $name = $this->check_input($session->get("name", ""));
            $surname = $this->check_input($session->get("surname", ""));
            $email = $this->check_input($session->get("email", ""));
            $phone = $this->check_input($session->get("phone", ""));
            $returntrip = $this->check_input($session->get("returntrip", ""));
            $cprice = $this->check_input($session->get("cprice", ""));
            $prepay = $this->check_input($session->get("prepay", ""));

            $selpassengers = $this->check_input($session->get("selpassengers", ""));
            $selsuitcases = $this->check_input($session->get("selsuitcases", ""));
            $selinfantseats = $this->check_input($session->get("selinfantseats", ""));
            $selchildseats = $this->check_input($session->get("selchildseats", ""));
            $selboosterseats = $this->check_input($session->get("selboosterseats", ""));
//			$selluggage = $this->check_input($session->get("selluggage", ""));
            $selcarry = $this->check_input($session->get("selcarry", ""));
            $vehicletype = $this->check_input($session->get("vehicletype", ""));

            $PickupAddr1 = $this->check_input($session->get("PickupAddr1", ""));
            $PickupAddr2 = $this->check_input($session->get("PickupAddr2", ""));
            $PickupAddr3 = $this->check_input($session->get("PickupAddr3", ""));
            $PickupAddr4 = $this->check_input($session->get("PickupAddr4", ""));
            $PickupAddr5 = $this->check_input($session->get("PickupAddr5", ""));
            $PickupAddr6 = $this->check_input($session->get("PickupAddr6", ""));

            $date1 = $this->check_input($session->get("date1", ""));
            $date2 = $this->check_input($session->get("date2", ""));
            $time1 = $this->check_input($session->get("time1", ""));
            $time2 = $this->check_input($session->get("time2", ""));
            $message = $this->check_input($session->get("message", ""));

            $begin = $this->check_input($session->get("begin", ""));
            $end = $this->check_input($session->get("end", ""));
            $from_dest = $this->check_input($session->get("temp1", ""));
            $to_dest = $this->check_input($session->get("temp2", ""));

            if ($from_dest == 0) {
                $begin = booking_helper::get_place_field($begin, 'title');
            }
            if ($to_dest == 0) {
                $end = booking_helper::get_place_field($end, 'title');
            }

            // now save this order
            $query = 'INSERT INTO #___taxibooking_orders SET '
                    . ' names = ' . $db->quote($name . ' ' . $surname) . ', '
                    . ' gender = ' . $db->quote($title) . ', '
                    . ' email = ' . $db->quote($email) . ', '
                    . ' phone = ' . $db->quote($phone) . ', '
                    . ' returntrip = ' . $db->quote($returntrip) . ', '
                    . ' cprice = ' . $db->quote($cprice) . ', '
                    . ' prepay = ' . $db->quote($prepay) . ', '
                    . ' selpassengers = ' . $db->quote($selpassengers) . ', '
                    . ' selinfantseats = ' . $db->quote($selinfantseats) . ', '
                    . ' selchildseats = ' . $db->quote($selchildseats) . ', '
                    . ' selboosterseats = ' . $db->quote($selboosterseats) . ', '
                    . ' selluggage = ' . $db->quote($selsuitcases) . ', '
                    . ' selcarry = ' . $db->quote($selcarry) . ', '
                    . ' PickupAddr1 = ' . $db->quote($PickupAddr1) . ', '
                    . ' PickupAddr2 = ' . $db->quote($PickupAddr2) . ', '
                    . ' PickupAddr3 = ' . $db->quote($PickupAddr3) . ', '
                    . ' PickupAddr4 = ' . $db->quote($PickupAddr4) . ', '
                    . ' PickupAddr5 = ' . $db->quote($PickupAddr5) . ', '
                    . ' PickupAddr6 = ' . $db->quote($PickupAddr6) . ', '
                    . ' datetime1 = ' . $db->quote(booking_helper::DateTime2($date1, $time1)) . ', '
                    . ' datetime2 = ' . $db->quote(booking_helper::DateTime2($date2, $time2)) . ', '
                    . ' message = ' . $db->quote($message) . ', '
                    . ' begin = ' . $db->quote($begin) . ', '
                    . ' end = ' . $db->quote($end) . ', '
                    . ' from_dest = ' . $db->quote($from_dest) . ', '
                    . ' to_dest = ' . $db->quote($to_dest) . ', '
                    . ' confirm = ' . $db->quote($hash_code) . ', '
                    . ' state = "-2", '
                    . ' driver_id = "",'
                    . ' payment = ' . $db->quote('ncipay') . ', '
                    . ' vehicletype = ' . $db->quote($vehicletype) . ', '
                    . ' created = NOW()';

            $db->setQuery($query);
            if (!$db->query()) {
                JError::raiseError(500, $db->getErrorMsg());
                return false;
            }
            $order_id = $db->insertid();

            $this->sendMailDetailsToOwner($order_id);


            // unset all the values
            $session->clear('cart');
            $session->clear('from_dest');
            $session->clear('to_dest');
            $session->clear('airports1');
            $session->clear('zipcode1');
            $session->clear('county1');
            $session->clear('seaports1');
            $session->clear('airports2');
            $session->clear('zipcode2');
            $session->clear('county2');
            $session->clear('seaports2');

            $session->clear('returnjurney');
            $session->clear('infantseats');
            $session->clear('chseats');
            $session->clear('boosterseats');
            $session->clear('vehicle');

            $session->clear('submittype');

            $session->clear('date1');
            $session->clear('time1');
            $session->clear('date2');
            $session->clear('time2');
            $session->clear('message');

            $session->clear('begin');
            $session->clear('end');
            $session->clear('temp1');
            $session->clear('temp2');

            $session->clear('title');
            $session->clear('name');
            $session->clear('surname');
            $session->clear('email');
            $session->clear('phone');
            $session->clear('returntrip');
            $session->clear('cprice');
            $session->clear('prepay');

            $session->clear('passengers');
            $session->clear('infantseats');
            $session->clear('chseats');
            $session->clear('boosterseats');
            $session->clear('suitcases');
            $session->clear('selpassengers');
            $session->clear('selsuitcases');
            $session->clear('selinfantseats');
            $session->clear('selchildseats');
            $session->clear('selboosterseats');
            $session->clear('selluggage');
            $session->clear('selcarry');
            $session->clear('vehicletype');

            $session->clear('PickupAddr1');
            $session->clear('PickupAddr2');
            $session->clear('PickupAddr3');
            $session->clear('PickupAddr4');
            $session->clear('PickupAddr5');
            $session->clear('PickupAddr6');

            // now redirects to the paypal site
            $itemname = "Taxi from [$begin] to [$end] on [$date1, $time1]";
            if ($returntrip)
                $itemname .= " and return"; // on [$date2, $time2].";

            $post_variables = array();
            $payment_url = "https://www.netcommercepay.com/iPAY/Default.asp";
            $this_item_price_total = $prepay * $cprice / 100;
            if ($elsettings->ncipay_currency == 422) {
                $this_item_price_total = round(($prepay * $cprice / 100));
            } else if ($elsettings->ncipay_currency == 840) {
                $this_item_price_total = round(($prepay * $cprice / 100), 2);
            }
            $post_variables["txtAmount"] = $this_item_price_total;
            $post_variables["txtCurrency"] = $elsettings->ncipay_currency;
            $post_variables["txtIndex"] = $order_id;
            $post_variables["txtMerchNum"] = $elsettings->ncipay_merchant_id;
            $post_variables["txthttp"] = JURI::base() . 'index.php?option=com_taxibooking&task=ncipay_return';
            //$post_variables["txthttp"]=substr($post_variables["txthttp"], 0, 50);
            $post_variables["Lng"] = $elsettings->ncipay_language;
            $post_variables["signature"] = MD5($post_variables["txtAmount"] . $post_variables["txtCurrency"] . $post_variables["txtIndex"] . $post_variables["txtMerchNum"] . $post_variables["txthttp"] . $elsettings->ncipay_secret_key);

            $ncipay_form = '<form name="ncipay_form" id="ncipay_form" action="' . $payment_url . '" enctype="application/x-www-form-urlencoded" method="post">';
            $ncipay_form .= '<input type="submit" src="http://www.netcommerce.com.lb/logo/NCseal_L.gif" border="0" alt="NetCommerce Security Seal" />';
            foreach ($post_variables as $name => $value) {
                if ($name == "txthttp") {
                    $ncipay_form .= '<input type="hidden" name="' . $name . '" value="' . $value . '" />';
                } else {
                    $ncipay_form .= '<input type="hidden" name="' . $name . '" value="' . htmlspecialchars($value) . '" />';
                }
            }
            $ncipay_form .= '</form>';

            $html = '<html><body>';
            $html.= JText::_('You will be redirected to NetCommerce iPay in a few seconds. If you are not, please click on the image link to complete your order.');
            $html.= $ncipay_form;
            $html.= '<script type="text/javascript">document.getElementById("ncipay_form").submit();</script>';
            $html.= '</body></html>';

            echo $html;
            exit();
        } elseif ($session->get('submittype') == 'Submitanzpay') {

            $title = $this->check_input($session->get("gender", ""));
            $name = $this->check_input($session->get("name", ""));
            $surname = $this->check_input($session->get("surname", ""));
            $email = $this->check_input($session->get("email", ""));
            $phone = $this->check_input($session->get("phone", ""));
            $returntrip = $this->check_input($session->get("returntrip", ""));
            $cprice = $this->check_input($session->get("cprice", ""));
            $prepay = $this->check_input($session->get("prepay", ""));

            $selpassengers = $this->check_input($session->get("selpassengers", ""));
            $selsuitcases = $this->check_input($session->get("selsuitcases", ""));
            $selinfantseats = $this->check_input($session->get("selinfantseats", ""));
            $selchildseats = $this->check_input($session->get("selchildseats", ""));
            $selboosterseats = $this->check_input($session->get("selboosterseats", ""));
//			$selluggage = $this->check_input($session->get("selluggage", ""));
            $selcarry = $this->check_input($session->get("selcarry", ""));
            $vehicletype = $this->check_input($session->get("vehicletype", ""));

            $PickupAddr1 = $this->check_input($session->get("PickupAddr1", ""));
            $PickupAddr2 = $this->check_input($session->get("PickupAddr2", ""));
            $PickupAddr3 = $this->check_input($session->get("PickupAddr3", ""));
            $PickupAddr4 = $this->check_input($session->get("PickupAddr4", ""));
            $PickupAddr5 = $this->check_input($session->get("PickupAddr5", ""));
            $PickupAddr6 = $this->check_input($session->get("PickupAddr6", ""));

            $date1 = $this->check_input($session->get("date1", ""));
            $date2 = $this->check_input($session->get("date2", ""));
            $time1 = $this->check_input($session->get("time1", ""));
            $time2 = $this->check_input($session->get("time2", ""));
            $message = $this->check_input($session->get("message", ""));

            $begin = $this->check_input($session->get("begin", ""));
            $end = $this->check_input($session->get("end", ""));
            $from_dest = $this->check_input($session->get("temp1", ""));
            $to_dest = $this->check_input($session->get("temp2", ""));

            if ($from_dest == 0) {
                $begin = booking_helper::get_place_field($begin, 'title');
            }
            if ($to_dest == 0) {
                $end = booking_helper::get_place_field($end, 'title');
            }

            $hash_code = uniqid();
            // now save this order
            $query = 'INSERT INTO #__taxibooking_orders SET '
                    . ' names = ' . $db->quote($name . ' ' . $surname) . ', '
                    . ' gender = ' . $db->quote($title) . ', '
                    . ' email = ' . $db->quote($email) . ', '
                    . ' phone = ' . $db->quote($phone) . ', '
                    . ' returntrip = ' . $db->quote($returntrip) . ', '
                    . ' cprice = ' . $db->quote($cprice) . ', '
                    . ' prepay = ' . $db->quote($prepay) . ', '
                    . ' selpassengers = ' . $db->quote($selpassengers) . ', '
                    . ' selinfantseats = ' . $db->quote($selinfantseats) . ', '
                    . ' selchildseats = ' . $db->quote($selchildseats) . ', '
                    . ' selboosterseats = ' . $db->quote($selboosterseats) . ', '
                    . ' selluggage = ' . $db->quote($selsuitcases) . ', '
                    . ' selcarry = ' . $db->quote($selcarry) . ', '
                    . ' PickupAddr1 = ' . $db->quote($PickupAddr1) . ', '
                    . ' PickupAddr2 = ' . $db->quote($PickupAddr2) . ', '
                    . ' PickupAddr3 = ' . $db->quote($PickupAddr3) . ', '
                    . ' PickupAddr4 = ' . $db->quote($PickupAddr4) . ', '
                    . ' PickupAddr5 = ' . $db->quote($PickupAddr5) . ', '
                    . ' PickupAddr6 = ' . $db->quote($PickupAddr6) . ', '
                    . ' datetime1 = ' . $db->quote(booking_helper::DateTime2($date1, $time1)) . ', '
                    . ' datetime2 = ' . $db->quote(booking_helper::DateTime2($date2, $time2)) . ', '
                    . ' message = ' . $db->quote($message) . ', '
                    . ' begin = ' . $db->quote($begin) . ', '
                    . ' end = ' . $db->quote($end) . ', '
                    . ' from_dest = ' . $db->quote($from_dest) . ', '
                    . ' to_dest = ' . $db->quote($to_dest) . ', '
                    . ' confirm = ' . $db->quote($hash_code) . ', '
                    . ' state = "-2", '
                    . ' driver_id = "",'
                    . ' payment = ' . $db->quote('authpay') . ', '
                    . ' vehicletype = ' . $db->quote($vehicletype) . ', '
                    . ' created = NOW()';

            $db->setQuery($query);
            if (!$db->query()) {
                JError::raiseError(500, $db->getErrorMsg());
                return false;
            }
            $order_id = $db->insertid();

            $this->sendMailDetailsToOwner($order_id);


            // unset all the values
            $session->clear('cart');
            $session->clear('from_dest');
            $session->clear('to_dest');
            $session->clear('airports1');
            $session->clear('zipcode1');
            $session->clear('county1');
            $session->clear('seaports1');
            $session->clear('airports2');
            $session->clear('zipcode2');
            $session->clear('county2');
            $session->clear('seaports2');

            $session->clear('returnjurney');
            $session->clear('infantseats');
            $session->clear('chseats');
            $session->clear('boosterseats');
            $session->clear('vehicle');

            $session->clear('submittype');

            $session->clear('date1');
            $session->clear('time1');
            $session->clear('date2');
            $session->clear('time2');
            $session->clear('message');

            $session->clear('begin');
            $session->clear('end');
            $session->clear('temp1');
            $session->clear('temp2');

            $session->clear('title');
            $session->clear('name');
            $session->clear('surname');
            $session->clear('email');
            $session->clear('phone');
            $session->clear('returntrip');
            $session->clear('cprice');
            $session->clear('prepay');

            $session->clear('passengers');
            $session->clear('infantseats');
            $session->clear('chseats');
            $session->clear('boosterseats');
            $session->clear('suitcases');
            $session->clear('selpassengers');
            $session->clear('selsuitcases');
            $session->clear('selinfantseats');
            $session->clear('selchildseats');
            $session->clear('selboosterseats');
            $session->clear('selluggage');
            $session->clear('selcarry');
            $session->clear('vehicletype');

            $session->clear('PickupAddr1');
            $session->clear('PickupAddr2');
            $session->clear('PickupAddr3');
            $session->clear('PickupAddr4');
            $session->clear('PickupAddr5');
            $session->clear('PickupAddr6');

            // now redirects to the anz site
            $itemname = "Taxi from [$begin] to [$end] on [$date1, $time1]";
            if ($returntrip)
                $itemname .= " and return"; // on [$date2, $time2].";
            $timestamp = time();

            $this_item_price_total = $prepay * $cprice / 100;

            $fp = "{$elsettings->auth_api_login_id}^{$order_id}^{$timestamp}^{$this_item_price_total}^";
            $transactionFP = hash_hmac("md5", $fp, $elsettings->auth_transcaction_key);
            if($elsettings->auth_test_mode)
                $url = 'https://test.authorize.net/gateway/transact.dll';
            else
                $url = 'https://secure.authorize.net/gateway/transact.dll';
            $auth_form = '<form id="authnet_form" method="post" action="'.$url.'">
<input type="hidden" name="x_FP_hash" value="' . $transactionFP . '">
<input type="hidden" name="x_FP_sequence" value="' . $order_id . '">
<input type="hidden" name="x_FP_timestamp" value="' . $timestamp . '">
<input type="hidden" name="x_login" value="' . $elsettings->auth_api_login_id . '">
<input type="hidden" name="x_type" value="AUTH_CAPTURE">
<input type="hidden" name="x_show_form" value="PAYMENT_FORM">
<input type="hidden" name="x_invoice_num" value="' . $order_id . '">
<input type="hidden" name="x_description" value="Taxi Booking by ' . $name . '">
<input type="hidden" name="x_cust_id" value="' . $name . ' ' . $surname . '">
<input type="hidden" name="x_amount" value="' . $this_item_price_total . '">
<input type="hidden" name="x_receipt_link_method" value="POST">
<input type="hidden" name="x_receipt_link_text" value="' . JText::_(AUTH_RETURN_MESSAGE) . '">
<input type="hidden" name="x_receipt_link_URL" value="' . JURI::base() . 'index.php?option=com_taxibooking&task=authnet_return&confirm=' . $hash_code . '">

</form>';
       // echo $auth_form;
       // die;

            $html = '<html><body>';
            $html.= JText::_('You will be redirected to AuthorizeNet Payment page in a few seconds.');
            $html.= $auth_form;
            $html.= '<script type="text/javascript">document.getElementById("authnet_form").submit();</script>';
            $html.= '</body></html>';

            echo $html;
            exit();
        }
    }

    function authnet_return() {
//        echo '<pre>';
//        var_dump($_REQUEST);

        $db = & JFactory::getDBO();
        $date = & JFactory::getDate();
        $elsettings = & booking_helper::config();
//        $mdHash = $elsettings->auth_api_login_id . $_REQUEST['x_trans_id'] . $_REQUEST['x_amount'];
//        $mdHash = md5($md5Hash);
//        if ($_REQUEST['x_MD5_Hash'] != $mdHash){
//            JError::raiseNotice("SOME_ERROR_CODE", "Some has code error");
//            JRequest::setVar( 'view', 'taxibooking' );
//    }

        $query = 'SELECT count(id)'
                . ' FROM #__taxibooking_auth_response'
                . ' WHERE order_id = ' . $_REQUEST["x_invoice_num"]
                . ' LIMIT 1';

        $db->setQuery($query);

        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        }

        $count = $db->loadResult();
        if ($count == 0) {
            $query = 'INSERT INTO #__taxibooking_auth_response SET '
                    . 'order_id =' . $_REQUEST['x_invoice_num'] . ','
                    . 'x_response_code ="' . $_REQUEST['x_response_code'] . '",'
                    . 'x_trans_id ="' . $_REQUEST['x_trans_id'] . '",'
                    . 'x_description ="' . $_REQUEST['x_description'] . '",'
                    . 'x_amount="' . $_REQUEST['x_amount'] . '"';

            $db->setQuery($query);

            if (!$db->query()) {

                JError::raiseError(500, $db->getErrorMsg());
                return false;
            } else {
                if ($_REQUEST['x_response_code'] == '1') {
                    $query = 'UPDATE #__taxibooking_orders SET authnetpay="' . $_REQUEST['x_amount'] . '" WHERE id=' . (int) $_REQUEST['x_invoice_num'];
                    $db->setQuery($query);
                    if (!$db->query()) {
                        JError::raiseError(500, $db->getErrorMsg());
                        return false;
                    } else {
                        JError::raiseNotice("SOME_ERROR_CODE", "Transacton was success at Authorizenet");
                    }
                } else {
                    JError::raiseNotice("SOME_ERROR_CODE", "Transacton was Declined for the following reason : " . $_REQUEST['x_response_reason_text']);
                }
            }
        }

        JRequest::setVar('view', 'thanks');
        parent::display();
    }

    /**
     * Receive paypal notification and take necessory action
     *
     * @access	public
     * @since	1.0
     */
    function paypal_notification() {
        global $mainframe, $option;

        //initialise variables
        $db = & JFactory::getDBO();
        $date = & JFactory::getDate();
        $elsettings = & booking_helper::config();

        //get data from request
        $post = JRequest::get('post');
        $custom = JRequest::getVar('custom', '', 'post');

        foreach ($post as $key => $value) {
            $pst .= $key . ": " . $value . "<br>\n";
        }

        $message = date(DATE_RFC822) . "<br><br>\n" . $pst . "<br>\n-----------------------------<br>\n end <br>\n";

        // paypal email
        $paypal_email = $elsettings->paypal_email; //vesconti@gmail.com
        // email address where script should send notifications
        $error_email = $elsettings->paypal_email; //vesconti@gmail.com
        // email header
        $em_headers = "From: The Seller <" . $elsettings->paypal_email . ">\n";  //vesconti@gmail.com
        $em_headers .= "Reply-To: " . $elsettings->paypal_email . "\n";
        $em_headers .= "Return-Path: " . $elsettings->paypal_email . "\n";
        $em_headers .= "Organization: company_name\n";
        $em_headers .= "X-Priority: 3\n";

        require_once (JPATH_COMPONENT . DS . 'classes' . DS . 'ipn_cls.php');

        $paypal_info = $post;
        echo $paypal_info;
        $paypal_ipn = new paypal_ipn($paypal_info);

        $memo = "";
        $payer_business_name = "";
        $pending_reason = "";
        $reason_code = "";

        foreach ($paypal_ipn->paypal_post_vars as $key => $value) {
            if (getType($key) == "string") {
                eval("\$$key=\$value;");
            }
        }

        $paypal_ipn->send_response();
        $paypal_ipn->error_email = $error_email;

        if (!$paypal_ipn->is_verified()) {
            $paypal_ipn->error_out("Bad order (PayPal says it's invalid)" . $paypal_ipn->paypal_response, $em_headers);
//				die();
            //echo "You have cancelled your transaction!";
        } else {

            switch ($paypal_ipn->get_payment_status()) {
                case 'Pending':

                    $pending_reason = $paypal_ipn->paypal_post_vars['pending_reason'];

                    if ($pending_reason != "intl") {
                        $paypal_ipn->error_out("Pending Payment - $pending_reason", $em_headers);
                        break;
                    }

                case 'Completed':

                    // get the order info
                    $query = 'SELECT cprice, names, prepay'
                            . ' FROM #__taxibooking_orders'
                            . ' WHERE confirm = ' . $custom
                            . ' LIMIT 1';

                    $db->setQuery($query);

                    if (!$db->query()) {
                        JError::raiseError(500, $db->getErrorMsg());
                        return false;
                    }

                    $config = $db->loadObject();

                    if ($paypal_ipn->paypal_post_vars['txn_type'] == "reversal") {
                        $reason_code = $paypal_ipn->paypal_post_vars['reason_code'];
                        $paypal_ipn->error_out("PayPal reversed an earlier transaction.", $em_headers);
                        // you should mark the payment as disputed now
                    } else {
                        //proverka !!!!!!!!!!!!!!!!!!!predpazvane ot hack!!!!!!!!!!!!!!!!!!!!!!!!!		
//echo "(trim($mc_gross)-$tax == ".$config['cprice'].") ";

                        if ((strtolower(trim($paypal_ipn->paypal_post_vars['business'])) == $paypal_email) && (trim($mc_gross) - $tax == ($config->prepay * $config->cprice / 100)) && (!empty($config->names))) {
                            $item_number = $custom; //za proverka i vryzka mejdu dvete tablici
                            // get the order info
                            $query = 'SELECT count(item_number)'
                                    . ' FROM #__taxibooking_paypal_table'
                                    . ' WHERE item_number = ' . $custom
                                    . ' LIMIT 1';

                            $db->setQuery($query);

                            if (!$db->query()) {
                                JError::raiseError(500, $db->getErrorMsg());
                                return false;
                            }

                            $count = $db->loadResult();

                            if ($count == 0) {
                                $query = 'INSERT INTO #__taxibooking_paypal_table SET '
                                        . ' payer_id = ' . $db->quote($payer_id) . ', '
                                        . ' payment_date = ' . $db->quote($payment_date) . ', '
                                        . ' txn_id = ' . $db->quote($txn_id) . ', '
                                        . ' first_name = ' . $db->quote($first_name) . ', '
                                        . ' last_name = ' . $db->quote($last_name) . ', '
                                        . ' payer_email = ' . $db->quote($payer_email) . ', '
                                        . ' payer_status = ' . $db->quote($payer_status) . ', '
                                        . ' payment_type = ' . $db->quote($payment_type) . ', '
                                        . ' memo = ' . $db->quote($memo) . ', '
                                        . ' item_name = ' . $db->quote($item_name) . ', '
                                        . ' item_number = ' . $db->quote($item_number) . ', '
                                        . ' quantity = ' . $db->quote($quantity) . ', '
                                        . ' mc_gross = ' . $db->quote($mc_gross) . ', '
                                        . ' mc_currency = ' . $db->quote($mc_currency) . ', '
                                        . ' address_name = ' . $db->quote($address_name) . ', '
                                        . ' address_street = ' . $db->quote(nl2br($address_street)) . ', '
                                        . ' address_city = ' . $db->quote($address_city) . ', '
                                        . ' address_state = ' . $db->quote($address_state) . ', '
                                        . ' address_zip = ' . $db->quote($address_zip) . ', '
                                        . ' address_country = ' . $db->quote($address_country) . ', '
                                        . ' address_status = ' . $db->quote($address_status) . ', '
                                        . ' payer_business_name = ' . $db->quote($payer_business_name) . ', '
                                        . ' payment_status = ' . $db->quote($payment_status) . ', '
                                        . ' pending_reason = ' . $db->quote($pending_reason) . ', '
                                        . ' reason_code = ' . $db->quote($reason_code) . ', '
                                        . ' txn_type = ' . $db->quote($txn_type);

                                $db->setQuery($query);
                                if (!$db->query()) {
                                    JError::raiseError(500, $db->getErrorMsg());
                                    return false;
                                } else {
                                    $paypal_ipn->error_out("This was a successful transaction", $em_headers);
                                }
                            } else {
                                $paypal_ipn->error_out("This was a duplicate transaction", $em_headers);
                                //echo "This transaction is already accepted or is dublicate transaction.";
                            }
                        } else {
                            $paypal_ipn->error_out("Someone attempted a sale using a manipulated URL", $em_headers);
                            //echo "Manipulated URL is using! ".$config['names'];
                        }
                    }
                    break;

                case 'Failed':
                    // this will only happen in case of echeck.
                    $paypal_ipn->error_out("Failed Payment", $em_headers);
                    //echo "Failed Payment";
                    break;

                case 'Denied':
                    // denied payment by us
                    $paypal_ipn->error_out("Denied Payment", $em_headers);
                    //echo "Denied Payment";
                    break;

                case 'Refunded':
                    // payment refunded by us
                    $paypal_ipn->error_out("Refunded Payment", $em_headers);
                    //echo "Refunded Payment";
                    break;

                case 'Canceled':
                    // reversal cancelled
                    // mark the payment as dispute cancelled		
                    $paypal_ipn->error_out("Cancelled reversal", $em_headers);
                    //echo "Cancelled Payment";
                    break;

                default:
                    // order is not good
                    $paypal_ipn->error_out("Unknown Payment Status - " . $paypal_ipn->get_payment_status(), $em_headers);
                    //echo "Unknown Payment Status. Please try later.";
                    break;
            }
        }
    }

    function paypal_cancel() {
        $msg = JText::_('You have cancelled your transaction!');
        $this->setRedirect(JRoute::_('index.php?option=com_taxibooking', false), $msg);
    }

    function paypal_thankyou() {
        $msg = JText::_('Thank you! We will send you an order confirmation e-mail shortly after we receive and check your order. If you do not receive the confirmation e-mail from us within 6 hours, please feel free to contact us and we will respond quickly.');
        $this->setRedirect(JRoute::_('index.php?option=com_taxibooking', false), $msg);
    }

    /**
     * Send Email to owner of the order
     *
     * @access	public
     * @since	1.0
     */
    function sendMailDetailsToOwner($order_id) {
        global $mainframe, $option;

        //initialise variables
        $db = & JFactory::getDBO();
        $date = & JFactory::getDate();
        $cur_date = $date->toFormat('%Y-%m-%d');
        $elsettings = & booking_helper::config();

        // get the order info
        $query = 'SELECT *'
                . ' FROM #__taxibooking_orders'
                . ' WHERE id = ' . $order_id;

        $db->setQuery($query);

        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        }

        $row_queue = $db->loadObject();

        $app = JFactory::getApplication();
        $site_name = $app->getCfg('sitename');


        /**
         * New Mail template
         */
        if ($row_queue->state == '1') {
            $order_status .= '<span style="color:green;">ACCEPTED</span>';
        } elseif ($row_queue->state == '0') {
            $order_status .= '<span style="color:red;">REJECTED</span>';
        } elseif ($row_queue->state == '-1') {
            $order_status .= '<span style="color:yellow;">ARCHIVED</span>';
        } elseif ($row_queue->state == '-2') {
            $order_status .= '<span style="color:green;">WAITING</span>';
        }

        $mailbody = '<table border="0">';
        $mailbody .= '<tr><td align="right"><img src="' . JURI::root() . 'images/stories/taxibooking/' . $elsettings->header_logo . '" alt="header_logo" border="0" /></td></tr>';
        $mailbody .= '<tr><td>&nbsp;</td></tr>';
        $mailbody .= '<tr><td align="left">' . $elsettings->header_info . '</td></tr>';
        $mailbody .= '<tr><td>&nbsp;</td></tr>';
        $mailbody .= '<tr><td><hr></td></tr>';
        $mailbody .= '<tr>
                            <td>
                                <table border="0" width="100%">
                                    <tr width="100%">
                                        <td width="50%">ORDER NO:&nbsp;&nbsp;&nbsp;' . str_pad($row_queue->id, 5, "0", STR_PAD_LEFT) . '</td>
                                        <td width="50%">
                                            ORDER STATUS:&nbsp;&nbsp;&nbsp;' . $order_status . '
                                        </td>
                                     </tr>
                                    <tr><td colspan="2"><hr></td></tr>

                                    <tr width="100%">
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Traveller information</span>
                                            <table border="0" width="100%">
                                                <tr width="100%">
                                                    <td width="30%">Passenger:</td>
                                                    <td width="70%">' . $row_queue->names . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">Email:</td>
                                                    <td width="70%">' . $row_queue->email . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">Phone:</td>
                                                    <td width="70%">' . $row_queue->phone . '</td>
                                                 </tr>
                                             </table>
                                        </td>
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Carrier Details</span>
                                            <table border="0" width="100%">';

        if ($row_queue->selpassengers > 0) {
            $mailbody .= '<tr width="100%">
                                                    <td width="45%">Passengers:</td>
                                                    <td width="55%">' . $row_queue->selpassengers . '</td>
                                                 </tr>';
        }
        if ($row_queue->selinfantseats > 0) {
            $mailbody .= '<tr width="100%">
                                                    <td width="45%">Infant seats:</td>
                                                    <td width="55%">' . $row_queue->selinfantseats . '</td>
                                                 </tr>';
        }
        if ($row_queue->selchildseats > 0) {
            $mailbody .= '<tr width="100%">
                                                    <td width="45%">Child seats:</td>
                                                    <td width="55%">' . $row_queue->selchildseats . '</td>
                                                 </tr>';
        }
        if ($row_queue->selboosterseats > 0) {
            $mailbody .= '<tr width="100%">
                                                    <td width="45%">Booster seats:</td>
                                                    <td width="55%">' . $row_queue->selboosterseats . '</td>
                                                 </tr>';
        }
        if ($row_queue->selluggage > 0) {
            $mailbody .= '<tr width="100%">
                                                    <td width="45%">Check-in Luggage:</td>
                                                    <td width="55%">' . $row_queue->selluggage . '</td>
                                                 </tr>';
        }

        $mailbody .= '     <tr width="100%">
                                                    <td width="45%">Vehicle type:</td>
                                                    <td width="55%">' . booking_helper::getvehicletype($row_queue->vehicletype) . '</td>
                                                 </tr>
                                            </table>
                                        </td>
                                     </tr>

                                     <tr><td colspan="2"><hr></td></tr>

                                    <tr width="100%">
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Pick-up Information</span>
                                            <table border="0" width="100%">
                                            <tr width="100%">
                                                    <td width="30%">Driver Name:</td>
                                                    <td width="70%">' . $row_queue->driver_id . '</td>
                                                 </tr>
                                                <tr width="100%">
                                                    <td width="30%">FROM:</td>
                                                    <td width="70%">' . $row_queue->begin . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->from_dest, 1) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr1 . '</td>
                                                 </tr>';

        if ($row_queue->from_dest == 1) {
            $mailbody .= '<tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->from_dest, 2) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr2 . '</td>
                                                </tr>
                                                <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->from_dest, 3) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr3 . '</td>
                                                </tr>';
        }

        $mailbody .= '<tr width="100%">
                                                <td width="30%">Date:</td>
                                                <td width="70%">' . booking_helper::DateTimeHuman($row_queue->datetime1) . '</td>
                                               </tr>';
        $mailbody .= '</table>
                                        </td>
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Drop-off Information</span>
                                            <table border="0" width="100%">
                                                <tr width="100%">
                                                    <td width="30%">TO:</td>
                                                    <td width="70%">' . $row_queue->end . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->to_dest, 1) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr4 . '</td>
                                                 </tr>';

        if ($row_queue->to_dest == 1) {
            $mailbody .= '<tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->to_dest, 2) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr6 . '</td>
                                                </tr>
                                                <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->to_dest, 3) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr6 . '</td>
                                                </tr>';
        }
        $mailbody .= '</table>
                                        </td>
                                     </tr>
                                  </table>
                               </td>
                             </tr>
                             <tr><td><hr></td></tr>';

        $mailbody .= ($row_queue->returntrip) ? '<tr><td>Date for your return trip:&nbsp;&nbsp;&nbsp;' . booking_helper::DateTimeHuman($row_queue->datetime2) . '</td></tr><tr><td><hr></td></tr>' : '';

        $mailbody .= ($row_queue->message != '') ? '<tr><td>Message:&nbsp;&nbsp;&nbsp;' . $row_queue->message . '</td></tr><tr><td><hr></td></tr>' : '';
        $mailbody .= '
                                     <tr>
                                        <td>
                                        <strong>
                                        Cost:&nbsp;&nbsp;' . $elsettings->currency_symbol . $row_queue->cprice . '
                                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                        Payment Method:&nbsp;&nbsp;' . strtoupper($row_queue->payment) . ' </strong>
                                        </td>
                                     </tr>
                                     <tr><td><hr></td></tr>

                                     <tr><td><center><b>Thank You & Have A Pleasant Journey.</b></center></td></tr>
                                     <tr>
                                        <td>
                                            <center>
                                            <span style="color:blue">Orders are subject to our terms & conditions. We welcome all comments on the services we provide.</span>
                                            </center>
                                        </td>
                                      </tr>
                                      <tr><td><hr></td></tr>
                                      <tr><td><center>Contact us:' . $elsettings->contact_info . '</center></td></tr>
                                </table>
                            </td>
                           </tr>';
        $mailbody .= '</table>';


        $mail = & JFactory::getMailer();
        $jconfig = new JConfig();
        $MailFrom = $jconfig->mailfrom;
        $FromName = 'Taxi Booking Authority - ' . $jconfig->fromname;
        $mail->setSender(array($MailFrom, $FromName));
        $mail->setSubject('Taxi Booking Notification : Order Id - ' . $order_id);
        $mail->setBody($mailbody);
        $mail->IsHTML(true);

        $mail->addRecipient($row_queue->email);

        $sent = $mail->Send();

        $query = 'SELECT #__users.id, #__users.email, #__users.name' .
                ' FROM #__users, #__usergroups' .
                ' WHERE (#__usergroups.id = 8 OR #__usergroups.id = 7) ' .
                ' AND #__users.sendEmail = 1 AND #__users.block = 0';
        $db->setQuery($query);
        if (!$db->query()) {
            JError::raiseError(500, $db->stderr(true));
            return;
        }
        $adminRows = $db->loadObjectList();

        // send email notification to admins
        foreach ($adminRows as $adminRow) {

            $mail = & JFactory::getMailer();

            $mail->setSender(array($MailFrom, $FromName));
            $mail->setSubject('Taxi book notification Order Id - ' . $order_id);
            $mail->setBody($mailbody);
            $mail->IsHTML(true);

            $mail->addRecipient($adminRow->email);

            $sent = $mail->Send();
        }

        return true;
    }

    /**
     * Show settings panel
     *
     * @access	public
     * @since	1.0
     */
    function showParams() {
        JRequest::setVar('tmpl', 'component'); //force the component template
        $component = JRequest::getCmd('component');

        if (empty($component)) {
            JError::raiseWarning(500, 'Not a valid component');
            return false;
        }

        // load the component's language file
        $lang = & JFactory::getLanguage();
        $lang->load($component);

        $model = $this->getModel('Params');
        $table = & JTable::getInstance('component');

        if (!$table->loadByOption($component)) {
            JError::raiseWarning(500, 'Not a valid component');
            return false;
        }

        require_once( JPATH_COMPONENT . DS . 'views' . DS . 'params' . DS . 'view.php' );

        $view = new TaxiBookingViewParams( );
        $view->assignRef('component', $table);
        $view->setModel($model, true);
        $view->display();
    }

    /**
     * Save the configuration
     */
    function saveParams() {
        // Check for request forgeries
        JRequest::checkToken() or jexit('Invalid Token');

        $component = JRequest::getCmd('component');

        $table = & JTable::getInstance('component');
        if (!$table->loadByOption($component)) {
            JError::raiseWarning(500, 'Not a valid component');
            return false;
        }

        $post = JRequest::get('post');
        $post['option'] = $component;
        $table->bind($post);

        // pre-save checks
        if (!$table->check()) {
            JError::raiseWarning(500, $table->getError());
            return false;
        }

        // save the changes
        if (!$table->store()) {
            JError::raiseWarning(500, $table->getError());
            return false;
        }

        //$this->setRedirect( 'index.php?option=com_config', $msg );
        $this->showParams();
    }

    function getCountyDistricts() {
        $db = JFactory::getDBO();
        $county = JRequest::getVar('county', 0);

        // get the county id
        $query = 'SELECT id'
                . ' FROM #__taxibooking_county'
                . ' WHERE title = ' . $db->quote(urldecode($county))
        ;
        $db->setQuery($query);
        $db->query();
        $county_id = $db->loadResult();

        $query = 'SELECT *'
                . ' FROM #__taxibooking_district'
                . ' WHERE county_id = ' . $county_id
                . ' AND published = 1'
                . ' ORDER BY ordering ASC'
        ;

        $db->setQuery($query);
        $items = $db->loadObjectList();

        $itemlist = array();
        $itemlist[] = JHTML::_('select.option', '', JText::_('SELECT DISTRICT'));
        if (!empty($items)) {
            foreach ($items as $item) {
                $itemlist[] = JHTML::_('select.option', $item->title, $item->title);
            }
        }

        echo JHTML::_('select.genericlist', $itemlist, 'district1', 'style="font-size:12px; width:250px"', 'value', 'text', '');

        exit();
    }

}

?>